#import "BpAlipayPlugin.h"
#import <AlipaySDK/AlipaySDK.h>

@interface BpAlipayPlugin()

@property (nonatomic, copy) FlutterResult callback;

@end

@implementation BpAlipayPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel
                                     methodChannelWithName:@"bp_alipay"
                                     binaryMessenger:[registrar messenger]];
    BpAlipayPlugin *instance = [[BpAlipayPlugin alloc] init];
    [registrar addApplicationDelegate:instance];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([@"isInstalled" isEqualToString:call.method]) {
        BOOL isInstalled = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay:"]];
        result([NSNumber numberWithBool:isInstalled]);
    } else if ([@"pay" isEqualToString:call.method]) {
        _callback = result;
        NSString *orderInfo = call.arguments;
        NSString *scheme = [self fetchUrlScheme];
        __weak typeof(self) weakSelf = self;
        [[AlipaySDK defaultService] payOrder:orderInfo
                                  fromScheme:scheme
                                    callback:^(NSDictionary *resultDic) {
            // H5情况下回调（未安装支付宝）
            [weakSelf onPayResultReceived:resultDic];
        }];
    } else {
        result(FlutterMethodNotImplemented);
    }
}

- (NSString *)fetchUrlScheme {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSArray *types = [infoDic objectForKey:@"CFBundleURLTypes"];
    for (NSDictionary *type in types) {
        if ([@"alipay" isEqualToString:[type objectForKey:@"CFBundleURLName"]]) {
            return [type objectForKey:@"CFBundleURLSchemes"][0];
        }
    }
    return nil;
}

#pragma mark - AppDelegate

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [self handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    return [self handleOpenURL:url];
}

- (BOOL)handleOpenURL:(NSURL *)url {
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        __weak typeof(self) weakSelf = self;
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                  standbyCallback:^(NSDictionary *resultDic) {
            [weakSelf onPayResultReceived:resultDic];
        }];
        return YES;
    }
    return NO;
}

- (void)onPayResultReceived:(NSDictionary *)resultDic{
    if(self.callback != nil){
        NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:resultDic];
        [mutableDictionary setValue:@"iOS" forKey:@"platform"];
        self.callback(mutableDictionary);
        self.callback = nil;
    }
}

@end
